package kr.moiba.user.web;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import kr.moiba.mail.MailSender;
import kr.moiba.user.domain.User;
import kr.moiba.user.service.UserSvc;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author 이 영호(Youngho Lee)
 */

@Controller
@RequestMapping("/user")
public class UserCtrl {
	
	private final Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private MessageSourceAccessor messages;
	
	@Autowired
	private MailSender mailSender;
	
	@Autowired
	private UserSvc userSvc;
	
	@RequestMapping(value={"/join.do"})
	public Map<String, Object> join(HttpServletRequest request) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		return resultMap;
	}
	
	@RequestMapping(value={"/form.do"})
	public Map<String, Object> form(HttpServletRequest request) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		Integer id = ServletRequestUtils.getIntParameter(request, "id");
		if(id != null){
			resultMap.put("user", userSvc.findby(id));
		}

		return resultMap;
	}
	
	@RequestMapping(value={"/submit.do"})
	public String submit(HttpServletRequest request, HttpSession session, User user) throws Exception {
		String ip = request.getRemoteAddr();
		String userId = (String)session.getAttribute("userId");
		user.setCreatedIp(ip);
		user.setCreatedId(userId);
		if(user.getAuthority().equals("ROLE_USER")){
			user.setEnabled(0);
		}else{
			user.setEnabled(1);
		}
		
		userSvc.add(user);

		return "user/result";
	}

	@RequestMapping("/chkDupl.do")
	public @ResponseBody String chkDuplication(HttpSession session, @RequestParam(required=true, value="userId")  String id) throws Exception {
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("chkDupl", true);
		condition.put("id", id);
		return userSvc.findbyChkDupl(condition);
	}

}